<template>
<div class="contain" id="reiForm">
  <div class="bill-line" v-if="expense.billno">单据编号：{{expense.billno}}</div>
  <div class="loader-base" v-if="showLoad"><div class="loader-wrap"></div></div>
  <header-box :title="'差旅费报销单申请'" :hasArrow="true"></header-box>
  <detail-user :showRemind = 'true'></detail-user>
  <progress-box :formData="true" @showLoadProgress="showLoadProgress"></progress-box>
  <div class="form-control displayflex">
    <div class="label">同行人</div>
    <div class="ipt-wrap flex1"><input type="text" placeholder="请填写同行人" v-model="expense.trippartner"/></div>
  </div>
  <div class="form-control displayflex">
    <div class="label require">出差事由</div>
    <!-- <div class="ipt-wrap flex1"><input type="text" style="ime-mode:active;" placeholder="请填写出差事由" v-model="expense.travelreasons"/></div> -->
    <div class="text-wrap flex1">
      <textarea rows="3" placeholder="请填写出差事由" v-model="expense.travelreasons"></textarea>
    </div>
  </div>
  <div class="form-control displayflex" @click="showbiztripF">
    <div class="label flex1">关联出差单</div>
    <div v-if="mybiztripapply.length>0">已关联{{mybiztripapply.length}}个</div>
    <div v-else class="remind">{{(mybiztripapplyList.length>0)?'请选择':'暂无出差单'}}</div>
    <i class="iconfont icon-arrow" v-if="mybiztripapplyList.length>0"></i>
  </div>
  <div class="form-control displayflex" @click="showovertimeF">
    <div class="label flex1">关联加班单</div>
    <div v-if="myovertimeapply.length>0">已关联{{myovertimeapply.length}}个</div>
    <div v-else class="remind">{{(myovertimeapplyList.length>0)?'请选择':'暂无加班单'}}</div>
    <i class="iconfont icon-arrow" v-if="myovertimeapplyList.length>0"></i>
  </div>

  <uploader-img class="required" :attaches="attaches" @getImgArr="getImgArr" ref="uploader" :reiImg="true"></uploader-img>

  <div class="rei-box" v-for="(item, index) in expenseItems">
    <div class="form-line displayflex">
      <i class="iconfont icon-coll"></i>
      <div class="flex1">报销明细（{{index+1}}）</div>
      <div class="del" @click="addAllItem(index)">复制</div>
      <div class="del" @click="deleItem(index)"
        v-if="index!=0">删除</div>
    </div>
    <div class="form-control displayflex">
      <popup-picker class="picker-wrap require" 
          title="出差类型" 
          :data="projectvalueList" 
          placeholder="请选择" 
          value-text-align="right"
          :show-name="true"
          v-model="item.projectvalue"></popup-picker>
      <i class="iconfont icon-arrow"></i>
    </div>
    <div class="form-control displayflex">
      <div class="label require">项目名称</div>
      <div class="ipt-wrap flex1"><input type="text" placeholder="请填写项目名称" v-model="item.projectname"/></div>
    </div>
    <div class="form-control displayflex">
      <x-address class="address-wrap require" 
        title="出发城市" 
        v-model="item.departurecode" 
        :list="addressData" 
        placeholder="请选择" 
        value-text-align="right"
        :hide-district="true">
      </x-address>
      <i class="iconfont icon-arrow"></i>
    </div>
    <div class="form-control displayflex">
      <x-address class="address-wrap require" title="目的城市" v-model="item.destinationcode" :list="addressData" placeholder="请选择" value-text-align="right" :hide-district="true">
      </x-address>
      <i class="iconfont icon-arrow"></i>
    </div>
    <div class="form-control displayflex">
      <div class="label require">开始时间</div>
      <div class="ctx-wrap flex1">
        <datetime v-model="item.starttime" 
          format="YYYY-MM-DD HH:mm:00"
          year-row="{value}年" month-row="{value}月" day-row="{value}日" hour-row="{value}时" minute-row="{value}分">{{item.starttime}}</datetime>
        <div v-if="!item.starttime" class="remind">请选择</div>
      </div>
      <i class="iconfont icon-arrow"></i>
    </div>
    <div class="form-control displayflex">
      <div class="label require">结束时间</div>
      <div class="ctx-wrap flex1">
        <datetime v-model="item.endtime" 
             format="YYYY-MM-DD HH:mm:00"
             year-row="{value}年" month-row="{value}月" day-row="{value}日" hour-row="{value}时" minute-row="{value}分">{{item.endtime}}</datetime>
        <div v-if="!item.endtime" class="remind">请选择</div>
      </div>
      <i class="iconfont icon-arrow"></i>
    </div>
    <div class="form-control displayflex lineb0" @click="fee(index)">
      <div class="label">费用类型</div>
      <div class="ctx-wrap flex1 remind">
        请选择
      </div>
      <i class="iconfont icon-arrow"></i>
    </div>
    <div class="detail-ticket cf">
      <div class="dt-box" v-for="subitem in item.travelitem" v-if="subitem.cost>0">
        <dl>
          <dt>{{subitem.name}}</dt> 
          <dd>{{subitem.cost}}</dd>
        </dl>
        <i class="close" @click="ticketDel(index,subitem.id)">×</i>
      </div>
    </div>
  </div>
  
  <div class="form-add" @click="addItem"><em>增加报销明细</em></div>
  <div class="btn-group displayflex">
    <div class="flex1 save" @click="changeImg(1)">保 存</div>
    <div class="flex1 submit" v-if="btnGroup.wfsubmit || !guid" @click="changeImg(2)">提 交</div>
    <div class="flex1 computed" @click="changeImg(3)">结算</div>
    <div class="dele" v-if="guid" @click="deleForm"><i class="iconfont icon-delbtn"></i></div>
  </div>
  <!-- 结算弹框 start-->
  <x-dialog v-model="show">
    <div class="dialog-settle">
      <div class="displayflex line1">合计差旅补助<i class="flex1"><em class="day blue">{{travelsubsidydays}}</em>天</i><em class="price blue">{{travelsubsidycost}}</em>元</div>
      <div class="displayflex line2">
        <div>报销总金额</div>
        <div class="flex1 blue">{{totalexpense}}元</div>
      </div>
      <i class="iconfont icon-close" @click="show=false;"></i>
      <div class="btn" @click="changeImg(2)">确定</div>
    </div>
  </x-dialog>
  <!-- 结算end  -->
  <!-- 费用类型start -->
  <popup v-model="showSettle">
    <div class="popup-settle">
      <div class="displayflex">
        <div class="flex1 btn-settle" @click="showSettle=false;">取消</div>
        <div class="flex1 btn-settle blue txt-rit" @click="getTickets">确定</div>
      </div>
      <div class="ticket-box" v-for="item in tickets">
        <div class="name">{{item.name}}</div>
        <div class="ipt"><input type="number" placeholder="请输入价格" v-model="item.cost"/></div>
      </div>
    </div>
  </popup>
  <!-- 费用类型end -->
  <!-- 出差单 start -->
  <popup v-model="showbiztrip" position="bottom" max-height="80%">
    <div class="popup-settle">
      <div class="popup-biztrip">
        <label class="remark-check" v-for="item in mybiztripapplyList">
          <input type="checkbox" class="ipt" name="remark" :value="item.guid" v-model="mybiztripapply">
          <span class="txt">{{item.caption}}</span>
        </label>
      </div>
    </div>
  </popup>
  <!-- 出差单 end -->
  <!-- 加班单 start -->
  <popup v-model="showovertime" position="bottom" max-height="80%">
    <div class="popup-settle">
      <div class="popup-biztrip">
        <label class="remark-check" v-for="item in myovertimeapplyList">
          <input type="checkbox" class="ipt" name="remark" :value="item.guid" v-model="myovertimeapply">
          <span class="txt">{{item.caption}}</span>
        </label>
      </div>
    </div>
  </popup>
  <!-- 加班单 end -->
</div>
</template>

<script>
import detailUser from "@/components/share/detailUser.vue";
import uploaderImg from "@/components/share/uploaderImg.vue";
import progressBox from "@/components/share/progress.vue";
import axios from "axios";

export default {
  components:{
    detailUser,
    uploaderImg,
    progressBox
  },
  data(){
    return {
      btnGroup:'',
      showLoad:false,
      showLoadT:false,
      showLoadP:false,
      show:false,
      expense:{},
      expenseItems:[{}],
      mybiztripapply:[],
      mybiztripapplyList:[],
      myovertimeapply:[],
      myovertimeapplyList:[],
      showSettle:false,
      tickets:[],
      choiceIndex:0,//选中的第几个明细
      demoTickets:[
          {
            name:'飞机票',
            id:'1',
            cost:'0.00'
          },{
            name:"火车票",
            id:'2',
            cost:'0.00'
          },{
            name:"汽车票",
            id:'3',
            cost:'0.00'
          },{
            name:'住宿费',
            id:'4',
            cost:'0.00'
          },{
            name:"市内交通费",
            id:'5',
            cost:'0.00'
          },{
            name:"其他",
            id:'6',
            cost:'0.00'
          }
      ],
      projectvalueList:[],
      showbiztrip:false,
      showovertime:false,
      totalexpense:0,
      travelsubsidydays:0,
      travelsubsidycost:0,
      savedGuid:'',

      attaches:[],
      fileattaches:[],
      attachesBase:[],

      dateLimit:[
        {
          date:'1970-01-01',
          hour:0
        }
      ],
    }
  },
  watch:{
    showLoadT(newVal, oldVal){
      if(this.showLoadT == false && this.showLoadP == false){
        this.showLoad = false;
      } else {
        this.showLoad = true;
      }
    },
    showLoadP(newVal, oldVal){
      if(this.showLoadT == false && this.showLoadP == false){
        this.showLoad = false;
      } else {
        this.showLoad = true;
      }
    },
  },
  computed: {
    userInfo(){
      return localStorage.UserInfo?JSON.parse(localStorage.UserInfo):'';
    },
    guid(){
      return this.$route.query.guid || "";
    },
    bizdataguid(){
      return this.$route.query.bizdataguid || "";
    },
  },
  created(){
    this.addressData = this.ChinaAddressV3Data;
    if(this.guid){
      this.getData();
      this.getBtn();
    };
    this.getInit();
  },
  methods:{
    //获取上传的图片
    getImgArr(val){
      this.attachesBase = val;
    },

    showbiztripF(){
      if(this.mybiztripapplyList.length>0){
        this.showbiztrip = true;
      }
    },

    showovertimeF(){
      if(this.myovertimeapplyList.length>0){
        this.showovertime = true;
      }
    },

    //初始化,获取关联表单
    getInit(){
      this.showLoadT = true;
      var data = {
                "staffid": this.userInfo.staffid
            };
      var _this = this;
      this.Ajax.post('ExpenseAccountService/MyExpenseAccountInit',data).then(function(resp) {
        if(resp.code == 'SUCC'){
          var result = JSON.parse(resp.data);
          // console.log(result,"差旅表单初始化")
          //出差表
          let apply =result.mybiztripapply;
          _this.mybiztripapplyList=apply;
          //加班表
          let overtime = result.myovertimeapply;
          _this.myovertimeapplyList=overtime;
          //出差类型
          var triptype = result.triptype,arr3=[];
          for(let i in triptype){
            var item = {
                value: triptype[i].value,
                name: triptype[i].caption
              };
            arr3.push(item);
          };
          _this.projectvalueList.push(arr3);
        }else{
          _this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: resp.message
          });
        };
        _this.showLoadT = false;
      });
    },

    //获取详情页
    getData(){
      var data = {
            "expense": {
              "guid": this.bizdataguid || this.guid
            }
          };
      var _this = this;
      _this.showLoadT = true;
      this.Ajax.post('ExpenseAccountService/GetExpenseAccountById',data).then(function(resp) {
        if(resp.code == 'SUCC'){
          
          var detailCtx = JSON.parse(resp.data);
          var expense = detailCtx.expense;

          if(detailCtx.attaches && detailCtx.attaches.length > 0){
            var attachesArr = detailCtx.attaches;
            var formatArr = ['gif','jpeg','jpg','png'];
            var picArr = [];
            for(let i in attachesArr){
              var url = attachesArr[i].url
              var format = url.split('.')[1];
              if(formatArr.indexOf(format)>-1){
                _this.attaches.push(attachesArr[i])
              }else{
                _this.fileattaches.push(attachesArr[i]);
              }
            }
          }

          _this.expense = expense;

          if(expense.biztripguid){
            _this.mybiztripapply=expense.biztripguid.split(',');
          };
          if(expense.overtimeguid){
            _this.myovertimeapply=expense.overtimeguid.split(',');
          };
      
          let expenseItems = detailCtx.items;
          for(let i in expenseItems){
            expenseItems[i].projectvalue = [expenseItems[i].projectvalue];
            expenseItems[i].starttime = expenseItems[i].starttime.replace("T"," ");
            expenseItems[i].endtime = expenseItems[i].endtime.replace("T"," ");
            expenseItems[i].departurecode = expenseItems[i].departurecode.split('/');
            expenseItems[i].destinationcode = expenseItems[i].destinationcode.split('/');
            expenseItems[i].travelitem = expenseItems[i].travelitem?JSON.parse(expenseItems[i].travelitem):'';
          };
          _this.expenseItems = expenseItems;

        }else{
          _this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: resp.message
          });
        }
        _this.showLoadT = false;
      });
    },

    //判断按钮权限（提交 撤回 审核）
    getBtn(){
      var data = {
                "bizguid": this.guid,
                "pagekey": "ExpenseAccountEdit",
                "staffid": this.userInfo.staffid,
                "todoguid": ""
            };
      var _this = this;
      _this.showLoadT = true;
      this.Ajax.post('ExpenseAccountService/WFAvailableButtons',data).then(function(resp) {
        if(resp.code == 'SUCC'){
          // console.log(JSON.parse(resp.data),"%%")
          _this.btnGroup = resp.data?JSON.parse(resp.data):'';
        }else{
          _this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: resp.message
          });
        }
        _this.showLoadT = false;
      });
    },

    addItem(){
      this.expenseItems.push({})
      let allH = document.getElementById("app").offsetHeight+353;
      this.$nextTick(function () {
        document.body.scrollTop = document.documentElement.scrollTop = allH;
      })
    },

    //结算
    settlement(result){
      this.showLoadT = true;
      this.totalexpense = 0;
      this.travelsubsidydays = 0;
      this.travelsubsidycost = 0;
      var _this = this;

      this.Ajax.post('ExpenseAccountService/MyExpenseAccountCompute',result).then(function(resp) {
        _this.showLoadT = false;
        if(resp.code == 'SUCC'){
          // console.log(JSON.parse(resp.data));
          let items = (JSON.parse(resp.data)).items;
          for(let i in items){
            _this.totalexpense = _this.totalexpense+items[i].totalexpense;
            _this.travelsubsidydays = _this.travelsubsidydays+items[i].travelsubsidydays;
            _this.travelsubsidycost = _this.travelsubsidycost+items[i].travelsubsidycost;
          };
        // } else if(step=="1"){
        } else {
          _this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: resp.message
          });
        }
      });
      this.show = true;
    },

    //展示费用
    fee(index){
      this.showSettle=true;
      this.choiceIndex = index;
      let result = this.expenseItems[index].travelitem;
      if(result){
        for(let i in result){
          result[i].cost = (result[i].cost>0)?result[i].cost:'';
        }
        this.tickets = result;
      }else{
        this.tickets = [
          {
            name:'飞机票',
            id:'1',
            cost:''
          },{
            name:"火车票",
            id:'2',
            cost:''
          },{
            name:"汽车票",
            id:'3',
            cost:''
          },{
            name:'住宿费',
            id:'4',
            cost:''
          },{
            name:"市内交通费",
            id:'5',
            cost:''
          },{
            name:"其他",
            id:'6',
            cost:''
          }
        ];
      };
    },

    //获取费用
    getTickets(){
      let result = this.tickets;
      let index = this.choiceIndex;
      this.expenseItems[index].travelitem = result;
      this.showSettle=false;
    },

    //删除费用
    ticketDel(index,id){
      let result = this.expenseItems[index].travelitem;
      for(let i in result){
        if(result[i].id == id){
          result[i].cost = '';
        }
      };
      this.expenseItems[index].travelitem = result;
    },

    //转换图片
    changeImg(step){
      const uploadApi = process.env.API_ROOT + '/app/openroute/CSBR.Management.AppService.Service.V1.DataService/FilesUpload';
      this.showLoadT = true;
      var attachesBase = this.attachesBase;
      var data = [];
      var _this = this;
      if(attachesBase.length == 0){
        this.save(step);
        return false;
      }
      for(let i in attachesBase){
        //接口调整图片前缀
        // let pic = attachesBase[i].indexOf('base64,') > -1?attachesBase[i].split('base64,')[1]:attachesBase[i];
        let pic = attachesBase[i].replace(/\n/g, '');

        let timestamp =new Date().getTime(),
            item = {
              "base64code" : pic,
            };
        data.push(item);
      };

      //new batch upload
      let reqList = [],
          resList = [],
          picNewArr = [],
          hasError = false;
      for(let i = 0; i < data.length; i++)
      {
        let item = [data[i]];
        let req = axios.post(uploadApi,item)
        reqList.push(req);
      }

      axios.all(reqList)
        .then(axios.spread(function(...resList) {
          resList.forEach((item) => {
            if(item.data.code == 'SUCC')
            {
              let url = JSON.parse(item.data.data)[0],
                  filename = url.split('/')[2],
                  result = {
                    type : null,
                    url : url,
                    fileid: null,
                    filename: filename
                  };
              picNewArr.push(result);
            }
            else
            {
              hasError = true;
            }
          });
          
          _this.attachesBase = [];
          _this.$refs.uploader.resetImgListBase();

          if(_this.attaches){
            _this.attaches = _this.attaches.concat(picNewArr);
          } else {
            _this.attaches = picNewArr;
          };

          if(hasError) {
            _this.showLoadT = false;
            _this.$vux.toast.show({
              type: "warn", //success, warn, cancel, text
              text: "部分图片上传发生错误，请重试"
            });
          } else {
            // console.log(_this.attaches);
            _this.save(step);
          }
        })
      );
      //new batch upload

      // this.Ajax.post('DataService/FilesUpload',data).then(function(resp) {
      //   if(resp.code == 'SUCC'){
      //     var picData = JSON.parse(resp.data);
      //     var picNewArr = [];
      //     for(let j in picData){
      //       let filename = picData[j].split('/')[2];
      //       var result = {
      //         type : null,
      //         url : picData[j],
      //         fileid: null,
      //         filename: filename
      //       };
      //       picNewArr.push(result);
      //       _this.attachesBase = [];
      //       _this.$refs.uploader.resetImgListBase();
      //     };
      //     if(_this.attaches){
      //       _this.attaches = _this.attaches.concat(picNewArr);
      //     } else {
      //       _this.attaches = picNewArr;
      //     };
      //     _this.save(step);
      //   }else{
      //     _this.showLoadT = false;
      //     _this.$vux.toast.show({
      //       type: "warn", //success, warn, cancel, text
      //       text: resp.message
      //     });
      //   }
      // });
    },

    //保存
    save(step){
      if(!this.checkForm()){
        this.showLoadT = false;
        return false;
      };

      if(!this.checkTimeOverlap()){
        this.showLoadT = false;
        return false;
      }

      var _this = this;
      this.showLoadT = true;

      //attaches定义附件合并，需要包含this.attaches和this.fileattaches;
      let mixedAttaches = [];
      if(this.attaches.length > 0){
        mixedAttaches = mixedAttaches.concat(this.attaches);
      }
      if(this.fileattaches.length > 0)
      {
        mixedAttaches = mixedAttaches.concat(this.fileattaches)
      }

      //明细表单数据格式转变
      var items = JSON.parse(JSON.stringify(this.expenseItems));//深度拷贝

      for(let i in items){
        //地址的文本格式变化
        let province = this.$options.filters["province"];
        let city = this.$options.filters["city"];
        items[i].departurepoint = province(items[i].departurecode[0])+'/'+city(items[i].departurecode[1]);
        items[i].destinationpoint = province(items[i].destinationcode[0])+'/'+city(items[i].destinationcode[1]);
        //地址的id格式变化
        items[i].departurecode = items[i].departurecode[0]+'/'+items[i].departurecode[1];
        items[i].destinationcode = items[i].destinationcode[0]+'/'+items[i].destinationcode[1];
        //费用类型金额格式变化
        let ticketItems = items[i].travelitem;
        if(!ticketItems){
          items[i].travelitem = this.demoTickets;
        }else{
          for(let j in ticketItems){
            ticketItems[j].cost = ticketItems[j].cost>0?ticketItems[j].cost:'0.00';
          }
        };
        items[i].travelitem = JSON.stringify(items[i].travelitem);
        //出差类型
        items[i].projectvalue = items[i].projectvalue[0];
      };
      var data = {
          "expense": {
              "billno": this.expense.billno || '',
              "guid": this.guid || '',  // GUID 非空则为修改 ，空则为新增
              "applicant": this.userInfo.name,
              "staffid": this.userInfo.staffid,
              "deptguid": this.userInfo.deptguid,
              "deptname": this.userInfo.deptname,
              "trippartner": this.expense.trippartner || '',
              "travelreasons": this.expense.travelreasons,
              "biztripguid":this.mybiztripapply.join(","),
              "overtimeguid": this.myovertimeapply.join(","),
              "attaches": mixedAttaches.length > 0 ? JSON.stringify(mixedAttaches):'',
          },
          // 明细行集合
          "items": items
      };

      //防止重复的判断
      if(this.savedGuid != '')
      {
        data.expense.guid = this.savedGuid;
      }
      // data.items.forEach((x) =>{
      //   alert(x.starttime + '====>' + x.endtime)
      // });
      // console.log(data,"差旅表单数据")
      //结算
      if(step == 3) {
        this.settlement(data);
      } else {  //保存
        this.Ajax.post('ExpenseAccountService/MyExpenseAccountSave',data).then(function(resp) {
          _this.showLoadT = false;
          if(resp.code == 'SUCC'){
            var allResult = (JSON.parse(resp.data)).expense;
            var guid = allResult.guid;
            _this.expense.billno = allResult.billno;
            _this.savedGuid = guid;
            //提交
            if(step=="2"){
              _this.submit(guid);
            }else{
              _this.$vux.toast.show({
                type: "success", //success, warn, cancel, text
                text: resp.message
              });
            }
          }else if(step=="1"){
            _this.$vux.toast.show({
              type: "warn", //success, warn, cancel, text
              text: resp.message
            });
          }
        });
      }
    },

    //提交
    submit(id){
      var data = { 
          "bizguid": id,///保存生成的guid,,,,
          "pagekey": "ExpenseAccountEdit", // 可用场景 MyBizTripApply    BizTripAudit
          "staffid": this.userInfo.staffid,
          "todoguid": "",
          "result": "Y",
          "rejectreason": ""
      };
      var _this = this;
      _this.showLoadT = true;
      this.Ajax.post('ExpenseAccountService/Submit',data).then(function(resp) {
        _this.showLoadT = false;
        if(resp.code == 'SUCC'){
          _this.$vux.toast.show({
            type: "success", //success, warn, cancel, text
            text: "提交成功",
            onHide () {
              _this.$router.go(-1);
            }
          });
        }else{
          _this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: resp.message
          });
        };
      });
    },

    //复制某条明细
    addAllItem(index){
      let curArr = JSON.parse(JSON.stringify(this.expenseItems)),
          item = curArr[index],
          clearlist = [
            'judgmentbasis',
            'dataversion',
            'departurepoint',
            'destinationpoint',
            'expenseaccountid',
            'guid',
            'isdeleted',
            'tenantguid',
            'totalexpense',
            'travelsubsidycost',
            'travelsubsidydays',
          ];
      clearlist.forEach((keyName) => { delete item[keyName] })
      this.expenseItems.push(item);
      let allH = document.getElementById("app").offsetHeight+512;
      this.$nextTick(function () {
        document.body.scrollTop = document.documentElement.scrollTop = allH;
      })
      
    },

    //删除某条明细
    deleItem(index){
      this.expenseItems.splice(index,1);
      this.dateLimit.splice(index,1);
    },

    //删除表单
    deleForm(){
      var _this = this;
      var data = {
                "expense": {
                    "guid": this.guid
                }
            };
      this.$vux.confirm.show({
        title:'提示',
        content: '确认删除申请吗？',
        onConfirm () {
          _this.showLoadT = true;
          _this.Ajax.post('ExpenseAccountService/MyExpenseAccountDelete',data).then(function(resp) {
            if(resp.code == 'SUCC'){
              _this.$vux.toast.show({
                type: "success", //success, warn, cancel, text
                text: resp.message,
                onHide () {
                  // _this.$router.push({
                  //   path:'/reimbursement/list'
                  // })
                  _this.$router.go(-1);
                }
              });
            }else{
              _this.$vux.toast.show({
                type: "warn", //success, warn, cancel, text
                text: resp.message
              });
            }
            _this.showLoadT = false;
          });
        }
      });
    },

    //表单验证
    checkForm(){
      if(!this.expense.travelreasons){
        this.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请填写出差事由"
        });
        return false;
      };
      // if(this.mybiztripapply.length==0){
      //   this.$vux.toast.show({
      //     type: "warn", //success, warn, cancel, text
      //     text: "请选择关联出差单"
      //   });
      //   return false;
      // };
      // 
      // ----------------图片必填验证start
      // if(this.attaches.length == 0){
      //   this.$vux.toast.show({
      //     type: "warn", //success, warn, cancel, text
      //     text: "请上传电子附件图片"
      //   });
      //   return false;
      // };
      // ----------------图片必填验证end
      // 
      // 循环表单明细
      let items = JSON.parse(JSON.stringify(this.expenseItems));
      for(let i in items){
        let index = new Number(i)+1;
        if(!items[i].projectvalue){
          this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: "请选择报销明细（"+index+"）的出差类型"
          });
          return false;
        };
        if(!items[i].projectname){
          this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: "请填写报销明细（"+index+"）的项目名称"
          });
          return false;
        };
        if(!items[i].departurecode){
          this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: "请选择报销明细（"+index+"）的出发城市"
          });
          return false;
        };
        if(!items[i].destinationcode){
          this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: "请选择报销明细（"+index+"）的目的城市"
          });
          return false;
        };
        if(!items[i].starttime){
          this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: "请选择报销明细（"+index+"）的开始时间"
          });
          return false;
        };
        if(!items[i].endtime){
          this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: "请选择报销明细（"+index+"）的结束时间"
          });
          return false;
        };
        if(items[i].starttime > items[i].endtime){
          // console.log(items[i].starttime, items[i].endtime)
          this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: "报销明细（"+index+"）的结束时间不能早于开始时间"
          });
          return false;
        }
        // travelitem
        // let totalNum = 0;
        // for(let j in items[i].travelitem){
        //   if(items[i].travelitem[j].cost>0){
        //     totalNum++;
        //   }
        // }
        // if(totalNum<1){
        //   this.$vux.toast.show({
        //     type: "warn", //success, warn, cancel, text
        //     text: "请选择报销明细（"+index+"）的费用类型"
        //   });
        //   return false;
        // };
      };
      return true;
    },

    //时间重叠检查
    checkTimeOverlap(){
      // alert('时间段检查开始')
      let argsStart = [],
          argsEnd = [];

      this.expenseItems.forEach((item) => {
        argsStart.push(new Date(Date.parse(item.starttime)).getTime());
        argsEnd.push(new Date(Date.parse(item.endtime)).getTime());
      });

      argsStart = argsStart.sort();
      argsEnd = argsEnd.sort();

      for(let i = 1; i < argsStart.length; i++){
        if (argsStart[i] < argsEnd[i-1]) {
          let pos = i+1;
          this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: "报销明细（"+ pos +"）的时间段有重叠"
          })
          alert('时间段检查不通过，发生重复')
          return false;
        }
      }
      // alert('时间段检查结束')
      return true;
    },

    showLoadProgress(val){
      this.showLoadP = val;
    }
  }
}
</script>